<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="广告名称" prop="advName">
        <el-input
          v-model="queryParams.advName"
          placeholder="请输入广告名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计费类型" prop="advChargingType">
        <el-select v-model="queryParams.advChargingType" placeholder="请选择广告计费类型" clearable size="small">
          <el-option
            v-for="item in defaultValue.advChargingType"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="跳转类型" prop="advLinkType">
        <el-select v-model="queryParams.advLinkType" placeholder="请选择广告跳转类型" clearable size="small">
          <el-option
            v-for="item in defaultValue.advLinkType"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否展示" prop="isShow">
        <el-select v-model="queryParams.isShow" placeholder="请选择是否展示" clearable size="small">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="展示时间" prop="advStartDate">
        <el-date-picker clearable size="small"
          v-model="queryParams.advStartDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:adv:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:adv:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:adv:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="advList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="广告名称" align="center" prop="adv_name" />
      <el-table-column label="广告位置" align="center" prop="adv_position_title" />
      <el-table-column label="跳转链接" align="center" prop="adv_link" />
      <el-table-column label="跳转类型" align="center" prop="adv_link_type" :formatter="formatLinkType" />
      <el-table-column label="开始时间" align="center" prop="adv_start_date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.adv_start_date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="adv_end_date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.adv_end_date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告价格" align="center" prop="adv_price" />
      <el-table-column label="最大点击数" align="center" prop="adv_max_click" />
      <el-table-column label="计费类型" align="center" prop="charging_type" :formatter="formatChargingType" />
      <el-table-column label="是否展示" align="center" prop="is_show">
        <template slot-scope="scope">
          <span v-if="scope.row.is_show === 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="nick_name" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:adv:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:adv:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="广告名称" prop="advName">
          <el-col :span="12">
            <el-input v-model="form.advName" placeholder="请输入广告名称" />
          </el-col>
        </el-form-item>
        <el-form-item label="广告描述" prop="advDesc">
          <el-col :span="12">
            <el-input type="textarea" v-model="form.advDesc" placeholder="请输入广告描述" />
          </el-col>
        </el-form-item>
        <el-form-item label="广告图片" prop="advImg">
          <el-col :span="12">
            <el-upload
              name="file"
              drag
              accept="image/*"
              :limit="1"
              :action="upload.uploadToOss"
              :headers="upload.uploadHeaders"
              :onError="uploadError"
              :onSuccess="uploadSuccess">
              <img v-if="form.advImg" :src="form.advImg" :width="200" />
              <i v-else class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-col>
        </el-form-item>
        <el-form-item label="广告跳转链接" prop="advLink">
          <el-col :span="12">
            <el-input v-model="form.advLink" placeholder="请输入广告跳转链接" />
          </el-col>
        </el-form-item>
        <el-form-item label="广告跳转类型" prop="advLinkType">
          <el-col :span="12">
            <el-select v-model="form.advLinkType" placeholder="请选择广告跳转类型">
              <el-option
                v-for="item in defaultValue.advLinkType"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="广告所在位置" prop="advPositionSign">
          <el-col :span="12">
            <el-select v-model="form.advPositionSign" placeholder="请选择广告所在位置">
              <el-option
                v-for="item in defaultValue.advPositionList"
                :key="item.advSign"
                :label="item.advPositionTitle"
                :value="item.advSign"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="广告展示开始时间" prop="advStartDate">
          <el-col :span="12">
            <el-date-picker clearable size="small"
              v-model="advTime"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="广告价格" prop="advPrice">
          <el-col :span="12">
            <el-input v-model="form.advPrice" placeholder="请输入广告价格" />
          </el-col>
        </el-form-item>
        <el-form-item label="广告计费类型" prop="advChargingType">
          <el-col :span="12">
            <el-select v-model="form.advChargingType" placeholder="请选择广告计费类型">
              <el-option
                v-for="item in defaultValue.advChargingType"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-col :span="12">
            <el-input-number :min="1" v-model="form.sort" placeholder="请输入排序" />
          </el-col>
        </el-form-item>
        <el-form-item label="是否展示" prop="isShow">
          <el-col :span="12">
            <el-radio v-model="form.isShow" label="1">是</el-radio>
            <el-radio v-model="form.isShow" label="0">否</el-radio>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAdv, getAdv, delAdv, addAdv, updateAdv, exportAdv, uploadToOss } from '@/api/app/adv'
import { getToken } from '@/utils/auth'
import { listPosition } from '@/api/app/position'

export default {
  name: "Adv",
  components: {
  },
  data() {
    return {
      upload: {
        uploadToOss: process.env.VUE_APP_BASE_API + "/common/uploadToOss",
        uploadHeaders: {
          Authorization: "Bearer " + getToken()
        }
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 广告表格数据
      advList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        advName: null,
        advStartDate: null,
        advEndDate: null,
        advChargingType: null,
        isShow: null,
      },
      defaultValue: {
        advChargingType: [
          {
            value: 0,
            label: '美肤计内部广告'
          },
          {
            value: 1,
            label: '点击量计费'
          },
          {
            value: 2,
            label: '时间计费'
          }
        ],
        advLinkType: [
          {
            value: 0,
            label: '没有跳转'
          },
          {
            value: 1,
            label: 'URL跳转'
          },
          {
            value: 2,
            label: '商品跳转'
          },
          {
            value: 3,
            label: '服务跳转'
          }
        ],
        advPositionList: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        advName: [
          { required: true, message: "广告名称不能为空", trigger: "blur" }
        ],
        advImg: [
          { required: true, message: "广告图片不能为空", trigger: "blur" }
        ],
        advLinkType: [
          { required: true, message: "广告跳转类型不能为空", trigger: "change" }
        ],
        advPositionSign: [
          { required: true, message: "广告所在位置不能为空", trigger: "blur" }
        ],
        advChargingType: [
          { required: true, message: "广告计费类型不能为空", trigger: "change" }
        ]
      },
      advTime: null
    };
  },
  created() {
    this.getList();
    this.getAdvPositionList();
  },
  methods: {
    /** 查询广告列表 */
    getList() {
      this.loading = true;
      listAdv(this.queryParams).then(response => {
        this.advList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAdvPositionList() {
      listPosition().then(response => {
        this.defaultValue.advPositionList = response.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        advId: null,
        advName: null,
        advDesc: null,
        advImg: null,
        advLink: null,
        advLinkType: null,
        advPositionSign: null,
        advStartDate: null,
        advEndDate: null,
        advPrice: null,
        advChargingType: null,
        advMaxClick: null,
        sort: null,
        isShow: "1"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.advId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const advId = row.adv_id || this.ids
      getAdv(advId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改广告";

        if (this.form.advStartDate) {
          this.advTime = [
            this.form.advStartDate,
            this.form.advEndDate
          ]

          this.form.advStartDate = null;
          this.form.advEndDate = null;
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.advTime) {
            this.form.advStartDate = this.advTime[0]
            this.form.advEndDate = this.advTime[1]
          }

          if (this.form.advId != null) {
            updateAdv(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAdv(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const advIds = row.adv_id || this.ids;
      this.$confirm('是否确认删除广告编号为"' + advIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAdv(advIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    handlePreview (file) {
      if (file.status === 'success') {
        this.imageVisiable = true
        this.$nextTick(() => {
          this.$refs.showImage.init(file.url)
        })
      }
    },
    uploadSuccess (response, file, fileList) {
      this.form.advImg = response.data
    },
    uploadError (response, file, fileList) {
      this.$message.error('上传图片失败！')
    },
    formatChargingType (row, column, cellValue) {
      let text = "";
      this.defaultValue.advChargingType.forEach(function (item) {
        if (item.value === row.adv_charging_type) {
          text = item.label
        }
      })

      return text;
    },
    formatLinkType (row, column, cellValue) {
      let text = "";
      this.defaultValue.advLinkType.forEach(function (item) {
        if (item.value === row.adv_link_type) {
          text = item.label
        }
      })

      return text;
    }
  }
};
</script>
